package xxy.com.customview.view;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

/**
 * Created by Administrator on 2017/12/6.
 */

public class MyButton extends android.support.v7.widget.AppCompatButton {
    int mLastx = 0;
    int mLasty = 0;
    int firstx = 0;
    int firsty = 0;
    private MyClick myClick;

    public MyButton(Context context) {
        super(context);
    }

    public MyButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 拖拽控件
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float deltax = 0;
        float deltay = 0;
        int x = (int) event.getRawX();   //根据屏幕返回控件的x坐标 而不是父布局
        int y = (int) event.getRawY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                firstx = x;
                firsty = y;
                break;
            case MotionEvent.ACTION_MOVE:
                deltax = x - mLastx;
                deltay = y - mLasty;
                setTranslationX( (int)getTranslationX() + deltax);   //getTranslationX()必须要加
                setTranslationY( (int)getTranslationY() + deltay);
                break;
            case MotionEvent.ACTION_UP:
                //根据第一次在ACTION_DOWN中记录的x y 坐标和最后一次event.getRawX() event.getRawY()记录的坐标，两者相减，如果为0，代表控件只是被点击但是没有移动，也就是这次事件只是一个点击事件
                if ((x - firstx) == 0 && (y - firsty) == 0) {
                    if (myClick != null) {
                        myClick.mClick();   //点击事件
                    }
                }
                break;
            default:
                break;
        }
        mLastx = x;
        mLasty = y;
        return true;
    }

    public interface MyClick {
        public void mClick();
    }

    public void setOnClickListener(MyClick myClick) {
        this.myClick = myClick;
    }
}
